package com.web.music.portal.mvc;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.servlet.mvc.SimpleFormController;

import com.web.music.interfaces.PersonService;
import com.web.music.interfaces.SecurityController;
import com.web.music.model.MusicBand;
import com.web.music.model.Person;

public class PersonFormController extends SimpleFormController {

	private PersonService personService;
	private SecurityController securityController;
	
	public PersonFormController() {
		setCommandClass(Person.class);
		setSessionForm(true);
	}
	
	@Override
	protected Object formBackingObject(HttpServletRequest request) {		
		Person person = new Person();
		person.setCreatedBy(securityController.getSessionUser(request));	
		// execute the following code only when going to display a form
		if (!isFormSubmission(request)){	
			String idString = request.getParameter("id");
			if (idString != null && !idString.equals("")) {
				long id = Long.parseLong(request.getParameter("id"));
				person = personService.getById(id);
			}			
		}		
		securityController.updateSecurityStatus(request, person);		
		return person;		
	}

	@Override
    protected Map<String,Object> referenceData(HttpServletRequest request) throws Exception 
    {
		Person person = new Person();
        Map<String,Object> refData = new HashMap<String,Object>();
		if (!isFormSubmission(request)){	
			String idString = request.getParameter("id");
			if (idString != null && !idString.equals("")) {
				long id = Long.parseLong(request.getParameter("id"));
				person = personService.getById(id);
			}			
		}	        
        List<MusicBand> allbands = person.getMusicBands();
        refData.put("allbands",allbands);            
        return refData;
    }
	
	@Override
	public void doSubmitAction(Object object){
		Person person = (Person)object;	

		if (person.getUpdateGranted()){ //Check if somebody does not "hack" url		
			personService.save(person);	
		}
	}

	public PersonService getPersonService() {
		return personService;
	}

	public void setPersonService(PersonService personService) {
		this.personService = personService;
	}
	public SecurityController getSecurityController() {
		return securityController;
	}

	public void setSecurityController(
			SecurityController securityController) {
		this.securityController = securityController;
	}	
}
